package com.cty.questions;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 计算两数之和，从一个数组中寻找两个元素他们相加之和 = 给定的 target
 *
 *
 */

class Solution {
    public static void main(String[] args) {
        int[] nums = {5,6,9,12};
        Solution solution = new Solution();
        int[] ints = solution.twoSum02(nums, 11);
        System.out.println("目标数组" + Arrays.toString(ints));
    }

    //暴力解法,时间复杂度O(n^2),空间复杂度O(1)
    public int[] twoSum01(int[] nums, int target) {
        for (int i = 0; i <= nums.length - 2;i++) {
            for (int j = i + 1;j <= nums.length - 1;j++) {
                if ((nums[i] + nums[j]) == target) {
                    return new int[]{i,j};
                }
            }
        }
        return null;
    }

    //哈希表法
    public int[] twoSum02(int[] nums,int target){
        int len = nums.length;
        Map<Integer, Integer> map = new HashMap<>(len - 1);
        map.put(nums[0],0);
        int key;
        for (int i = 1;i < len;i++) {
            key = target - nums[i];
            if (map.containsKey(key)) {
                return new int[]{i,map.get(key)};
            }
            map.put(nums[i], i);
        }
        return null;
    }
}
